package com.jinit.jia.boot.web.servlet.context;

import com.jinit.jia.boot.autoconfigure.web.servlet.TomcatServletWebServerFactory;
import com.jinit.jia.boot.web.context.ConfigurableWebServerApplicationContext;
import com.jinit.jia.boot.web.server.WebServer;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContextException;
import org.springframework.web.context.support.GenericWebApplicationContext;

import javax.servlet.ServletContext;
import java.util.Enumeration;

/**
 * ServletWebServerApplicationContext
 *
 * @author JInit
 * @date 2021-08-06
 */
public class ServletWebServerApplicationContext extends GenericWebApplicationContext
        implements ConfigurableWebServerApplicationContext {
    /**
     * web服务
     */
    private volatile WebServer webServer;

    @Override
    public final void refresh() throws BeansException, IllegalStateException {
        try {
            super.refresh();
        }
        catch (RuntimeException ex) {
            throw ex;
        }
    }

    @Override
    protected void onRefresh() {
        super.onRefresh();
        try {
            // 获取嵌入式的Servlet容器工厂，并通过工厂来获取Servlet容器
            // 简化：仅实现tomcat容器工厂
            createWebServer();
        }
        catch (Throwable ex) {
            throw new ApplicationContextException("Unable to start web server", ex);
        }
    }

    /**
     * 创建web 服务
     */
    private void createWebServer() {
        WebServer webServer = this.webServer;
        ServletContext servletContext = getServletContext();
        if (webServer == null && servletContext == null) {
            // 先获取嵌入式Servlet容器工厂
            TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
            this.webServer = factory.getWebServer();
        }
        else if (servletContext != null) {
            Enumeration<String> attributeNames = servletContext.getAttributeNames();
            // TODO: webServer不为空，待实现初始化器的onStartUp

        }
        initPropertySources();
    }

    /**
     * 获取web server工厂
     * 仅实现tomcat 服务工厂
     * @return
     */
    protected TomcatServletWebServerFactory getWebServerFactory() {
        TomcatServletWebServerFactory factory = getBeanFactory().getBean(TomcatServletWebServerFactory.class);
        return factory;
    }

}
